/**
* @CopyRight tstudy.com.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.weike;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.ResponseHandlerInterface;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.BaseOnScrollListener;
import com.tstudy.laoshibang.base.BaseOnScrollListener.LoadMoreCallBack;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.CONSTANT.LoadType;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.manager.SearchHistoryManager;
import com.tstudy.laoshibang.mode.SearchHistory;
import com.tstudy.laoshibang.mode.Weike;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.mode.response.WeikeListResponse;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;
import com.tstudy.laoshibang.weike.WeikeListAdapter.AdapterCallBack;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
@SuppressLint("InflateParams")
@EFragment(R.layout.weike_search)
public class WeikeSearchFragment extends BaseFragment{
	static String TAG = "weike_search";
	public WeikeSearchFragment() {
		super();
	}
	
	@ViewById(R.id.weike_search_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.weike_search_progress)
	RelativeLayout mProgressLayout;
	
	@ViewById(R.id.weike_search_empty_layout)
	RelativeLayout mEmptyLayout;
	
	@ViewById(R.id.weike_search_list)
	PullToRefreshListView mPullToRefreshListView;
	@ViewById(R.id.weike_search_ext)
	EditText mSearchExt;
	
	@StringRes(R.string.search_history_clear)
	String clearStr;
	int mIndexMargin = CommonUtil.dip2px(6);
	
	BaseOnScrollListener mBaseOnScrollListener;
	LoadType mLoadType;
	
	String mWord;
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;
	WeikeListAdapter mWeikeListAdapter;
	SearchHistoryAdapter mSearchHistorydapter;
	List <SearchHistory> mSearchHistory = new ArrayList<SearchHistory>();
	List <Weike> mWeikes = new ArrayList<Weike>();
	boolean isSearch;

	public static void add(int containerViewId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,WeikeSearchFragment_.class.getName(),args);
		((BaseActivity)BaseApplication.mCurrentActivity).add(containerViewId,fragment,TAG);	
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			mRootLayout.setOnClickListener(null);
			mWeikeListAdapter = new WeikeListAdapter();
			mWeikeListAdapter.setAdatperCallBack(new AdapterCallBack() {
				@Override
				public void onAvatorClick(int weikeId,int position) {
					WeikeDetailPlayerFragment.add(mFragmentId,weikeId,position);
				}

				@Override
				public void onLoveClick(Weike weike, int position,TextView view) {
					if (BaseApplication.checkLogin()) {
						loveAction(weike, CONSTANT.ASSO_TYPE_WEIKE, weike.isPraise==0?CONSTANT.UNLOVE_ACTION:CONSTANT.LOVE_ACTION, view);
					}
				}
			});
			mPullToRefreshListView.setMode(Mode.DISABLED);
			mSearchHistorydapter = new SearchHistoryAdapter();
			mSearchHistorydapter.setAdatperCallBack(new com.tstudy.laoshibang.weike.SearchHistoryAdapter.AdapterCallBack() {
				@Override
				public void onViewClick(String name) {
					mSearchExt.setText(name);
					searchAction();
				}
			});
			mSearchExt.setFocusable(true);
			mSearchExt.setFocusableInTouchMode(true);
			mSearchExt.requestFocus();
			//searchExt.setHint(R.string.search_product_hint);
			mSearchExt.setText(mWord);
			setSearchHistoryData();
			mSearchExt.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					mSearchExt.setFocusable(true);
					setSearchHistoryData();
				}
			});
//			mSearchExt.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
//				@Override
//				public void onFocusChange(View v, boolean hasFocus) {
//					if (hasFocus) {
//						setSearchHistoryData();
//					} else {
//						
//					}
//				}
//			});
			mSearchExt.setOnEditorActionListener(new OnEditorActionListener() {
				@Override
				public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//					if(actionId == EditorInfo.IME_ACTION_SEARCH){
					if (event == null) {
						searchAction();
					}
//					}
					return false;
				}
			});
//			mLoadType = LoadType.load_first;
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
//					getActiveList();
					showSoftKeyBoard(mSearchExt,true);
				}
			},CONSTANT.LOAD_DATA_DELAY_TIME);
			mBaseOnScrollListener = new BaseOnScrollListener(new LoadMoreCallBack() {
				@Override
				public void loadMore() {
					mPullToRefreshListView.startLoadMore();
					mLoadType = LoadType.load_more;
					getWeikeList();
				}
			});
			mPullToRefreshListView.setOnScrollListener(mBaseOnScrollListener);
			mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					mLoadType = LoadType.load_refresh;
					getWeikeList();
				}
			});
		}
	}
	
	@Click(R.id.weike_search_back)
	public void back(){
		backAction(mFragmentId);
		showSoftKeyBoard(mSearchExt, false);
	}
	public void setSearchHistoryData(){
		mSearchHistory = (List<SearchHistory>) SearchHistoryManager.getInstance().queryByField("type", SearchHistory.TYPE_WEIKE);
		if (mSearchHistory != null && mSearchHistory.size() > 0) {
			SearchHistory clearObj = new SearchHistory(clearStr,0,SearchHistory.TYPE_WEIKE);
			mSearchHistory.add(clearObj);
		}
		mPullToRefreshListView.setAdapter(mSearchHistorydapter);
		mSearchHistorydapter.setData(mSearchHistory);
		
	}
	private void getWeikeList(){
		if (mIsLoading) {
			return ;
		}
		if (mLoadType == LoadType.load_more) {
			start += pageSize;
//			limit += pageSize;
		}else{
			start = 0;
			limit = pageSize;
		}
		mIsLoading = true;
		ResponseHandlerInterface response = new BaseListJsonHandler<WeikeListResponse>() {
			public void onStart() {
				if (mLoadType == LoadType.load_first) {
					showProgressBar(mProgressLayout);
				}
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, WeikeListResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.getData() != null) {
						if (mLoadType == LoadType.load_more) {
							if (mWeikes.size() == response.getData().getCount()) {
								mBaseOnScrollListener.mIsEnd = true;
							}
						}else{
							mWeikes.clear();
						}
						List<Weike> list = response.getData().getList();
						if (list != null) {
							mWeikes.addAll(list);
						}
						mPullToRefreshListView.setAdapter(mWeikeListAdapter);
						if (mWeikes.size() > 0) {
							mEmptyLayout.setVisibility(View.GONE);
						}else{
							mEmptyLayout.setVisibility(View.VISIBLE);
						}
						mWeikeListAdapter.setData(mWeikes);
					}
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					WeikeListResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected WeikeListResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,WeikeListResponse.class);
			}
		};
		HttpManager.getInstance().getWeikeList(BaseApplication.mUserNo,start,limit, mWord,null,0, response);
	}
	
	/**
	 * 微课点赞
	 * @param activeId
	 * @param type
	 * @param isPraise
	 */
	private void loveAction(final Weike weike,int type,final int isPraise,final TextView loveCountTxt){
		BaseListJsonHandler<BaseResponse> response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
//					int count = weike.isPraise==1?weike.praiseNum-1:weike.praiseNum +1;
//					loveCountTxt.setText(count+"");
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().loveAction(BaseApplication.mUserNo, type, weike.coseId, isPraise, null,response);
	}

	public void afterLoading(){
		mIsLoading = false;
		hideProgressBar(mProgressLayout);
		if(mLoadType == LoadType.load_more){
			if (mBaseOnScrollListener.mIsEnd) {
				mPullToRefreshListView.endLoadMore(BaseApplication.getResString(R.string.weike_no_more_data));
			}else{
				mPullToRefreshListView.stopLoadMore();
			}
		}
		if(mPullToRefreshListView != null){
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if(mPullToRefreshListView != null){
						mPullToRefreshListView.onRefreshComplete();
						LogUtil.d("--onRefreshComplete afterloading");
					}
				}
			}, 1000);
		}
	
	}
	public void searchAction(){
		mSearchExt.clearFocus();
		mSearchExt.requestFocus();
		showSoftKeyBoard(mSearchExt, false);
		mWord = mSearchExt.getText().toString();
		if (!TextUtils.isEmpty(mWord)) {
			SearchHistory searhcHistory = new SearchHistory(mWord,System.currentTimeMillis(),SearchHistory.TYPE_WEIKE);
			SearchHistoryManager.getInstance().insertOrUpdate(searhcHistory);
		}
		mLoadType = LoadType.load_first;
		getWeikeList();
	}
	@Override
	public void clear() {
		showSoftKeyBoard(mSearchExt,false);
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
		}
	}

}
